package com.yy.satokenapplication.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.yy.satokenapplication.entity.SysUser;
import com.yy.satokenapplication.exception.GlobalExceptionHandler.Result;
import com.yy.satokenapplication.model.request.LoginRequest;
import com.yy.satokenapplication.model.response.LoginResponse;
import com.yy.satokenapplication.service.impl.SysUserServiceImpl;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    @Resource
    private CacheManager cacheManager;
    
    private final SysUserServiceImpl userService;

    
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody LoginRequest request) {

        // 验证用户名和密码
        SysUser user = userService.getUserByUsername(request.getUsername());
        if (user == null || !userService.checkPassword(request.getPassword(), user.getPassword())) {
            return Result.fail(401, "用户名或密码错误");
        }
        
        // 登录成功，生成token
        StpUtil.login(user.getId());
        //如果想让token携带更多信息，可以使用SaLoginModel或者SaLoginConfig来设置更多信息，比如：
        // StpUtil.login(user.getId(), SaLoginConfig.setDevice("web").setExtra("ip", "127.0.0.1"));
        
        // 返回登录信息
        LoginResponse response = new LoginResponse();
        response.setToken(StpUtil.getTokenValue());
        return Result.success(response);
    }
    
    @PostMapping("/logout") 
    public Result<String> logout(@RequestParam(name = "userId") Long userId) {
        cacheManager.getCache("permissions").evict(userId);
        cacheManager.getCache("roles").evict(userId);
        StpUtil.logout(userId);
        return Result.success("用户已退出");
    }
} 